<template>
	<view>
		<view class="box" style="flex: 1; height: 642px">
			<view class="chat-text"
				style="height: 580px; border-bottom: 1px solid #ddd; overflow-y: auto; font-size: 15px;">
				<view style="margin-bottom: 20px" v-for="item in chatList">
					<!-- 左边的聊天消息开始 -->
					<view v-if="item.chatUserId === item.roleId" style="display: flex; grid-gap: 10px">
						<image :src="item.userAvatar" style="width: 50px; height: 50px; border-radius: 5px" alt="">
							<view style="max-width: 50%; width: fit-content">
								<view style="color: #666; margin-bottom: 5px">{{ item.userName }}</view>
								<view style="background-color: #d1e7ff; padding: 12px; border-radius: 5px;">
									{{item.text}}
								</view>
							</view>
					</view>
					<!-- 左边的聊天消息结束 -->

					<!-- 右边的聊天消息开始 -->
					<view v-if="item.userId === item.roleId"
						style="display: flex; justify-content: right; grid-gap: 10px">
						<view style="max-width: 50%; width: fit-content">
							<view style="color: #666; margin-bottom: 5px; text-align: right">{{ item.userName }}</view>
							<view style="background-color: #a3eecb; padding: 10px; border-radius: 5px;">{{item.text}}
							</view>
						</view>
						<image :src="item.userAvatar" style="width: 50px; height: 50px; border-radius: 5px" alt="">
					</view>
					<!-- 右边的聊天消息结束 -->
				</view>
				<view style="height: 0"><a id="chat-text-end" name="1" href="#1" style="outline: none">&nbsp;</a></view>
			</view>
			<!-- 聊天输入框开始 -->
			<view class="chat-input-container" style="height: 60px; position: relative;">
				<textarea v-model="text" style="height: 60px; width: 85%; padding: 20px; border: none; font-size: 12px;
	    border-bottom: 1px solid #ddd; outline: none;" />
				<view style="position: absolute; right: 10px; bottom: 15px;">
					<button type="primary" size="mini" @click="send()">发送</button>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: uni.getStorageSync('xm-user'),
				chatGroupList: [],
				role: '',
				chatId: '',
				text: '',
				role: "",
				chatList: [],

			}
		},
		onLoad(option) {
			this.chatId = option.chatId;
			this.role = option.role;
		},
		onShow() {
			this.loadChatList(this.chatId, this.role)
		},
		methods: {
			loadChatList(chatId, role) {
				this.form = {}
				this.role = role
				this.$request.get(`/chatInfo/selectUserChat/${chatId}/${role}`).then(res => {
					this.chatList = res.data || [];
				});
			},
			send() {
				if (this.text === '') { // 直接使用传入的text参数进行校验
					uni.showToast({
						icon: 'error',
						title: '发送消息不能为空'
					})
					return;
				}
				const formData = {
					chatUserId: this.chatId,
					userId: this.user.id,
					text: this.text,
					role: this.role // 直接在formData中添加role属性
				};
				this.$request.post('/chatInfo/add', formData).then(res => {
					this.text = ''; // 清空form对象
					this.loadChatList(this.chatId, this.role);
				})
			},
		}
	}
</script>

<style>

</style>